package com.example.kevin.gps;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.AndroidException;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;


public class MainActivity extends Activity   {

    //varibles for Network connection
    private Socket csocket;
    private static final int serverPort = 80;
    private static final String serverIP = "192.168.1.110";

    //varibles for GPS data

    TextView LatBox;
    TextView LongBox;
    TextView ButtonT;
    double latitude;
    double longitude;
    boolean flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        flag = false;
        latitude =0;
        longitude =0;
        //create an AsyncTask task to connect to the server
        ConnectServer task = new ConnectServer();
        task.execute();

        //find the textboxes so that we can infor the user of their lat/long
        LatBox = (TextView) findViewById(R.id.LatBox);
        LongBox = (TextView) findViewById(R.id.LongBox);
        ButtonT = (TextView) findViewById(R.id.button);

        //get the location from the location context and create a listener for it.
        LocationManager LM = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener LL = new mylocationlistener();

        //recive update every 0 ms and if we have change 0
        LM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, LL);
    }

         class mylocationlistener implements LocationListener{

             @Override
             public void onLocationChanged(Location location){
                 if(location != null) {
                     longitude = location.getLongitude();
                     latitude = location.getLatitude();

                     LatBox.setText(Double.toString(latitude));
                     LongBox.setText(Double.toString(longitude));
                 }

             }

             @Override
             public void onStatusChanged(String provider,int status, Bundle extras){}

             @Override
             public void onProviderEnabled(String provider){}

             @Override
             public void onProviderDisabled(String provider){}


        }


    private class ConnectServer extends AsyncTask<Void,Void,Void> {


        @Override
        protected Void doInBackground(Void... params) {

            try {
                //convert the IP address to InetAddress object and try and bind to the server
                InetAddress serverAddr = InetAddress.getByName(serverIP);
                csocket = new Socket(serverAddr, serverPort);
            } catch (UnknownHostException e1) {

                e1.printStackTrace();

            } catch (IOException e1) {

                e1.printStackTrace();

            }
            while(true) {
                while (flag){


                    try {
                        Calendar cal = Calendar.getInstance();
                        String str = Double.toString(latitude) + "," + Double.toString(longitude) + "," + Long.toString(cal.getTimeInMillis());


                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(csocket.getOutputStream())), true);
                        out.println(str);

                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }


             //return null;
        }



    }

    public void onClick(View view) {

        if(flag)
        {
            ButtonT.setText("Start");
            flag=false;

        }else{
            ButtonT.setText("Stop");
            flag=true;

        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}
